﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.Log;

namespace WinFormApp
{
    public partial class FTestThread : Form
    {
        public FTestThread()
        {
            InitializeComponent();
        }

        private void FTestThread_Load(object sender, EventArgs e)
        {
            try
            {
                checkBoxLockLog.Checked = logControl.IsLock;
                checkBoxLockLog.CheckedChanged += CheckBoxLockLog_CheckedChanged;

                UtilZ.Dotnet.Ex.ZLog.ZLoger.OutputOption = UtilZ.Dotnet.Ex.ZLog.ZLogerOutputOptions.Loger;
                var redirectAppenderToUI = (RedirectAppender)Loger.GetAppenderByName(null, "RedirectToUI");
                if (redirectAppenderToUI != null)
                {
                    redirectAppenderToUI.RedirectOuput += RedirectLogOutput;
                }
                else
                {
                    this.logControl.AddLog(string.Format("{0} {1}", DateTime.Now.ToString(LogConstant.DateTimeFormat), "日志配置文件不存在"), LogLevel.Warn);
                }
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
            }
        }


        private void RedirectLogOutput(object sender, RedirectOuputArgs e)
        {
            try
            {
                if (this.IsDisposed)
                {
                    return;
                }

                this.logControl.AddLog(string.Format("{0} {1}", e.Item.Time.ToString(LogConstant.DateTimeFormat), e.Item.Content), e.Item.Level);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void CheckBoxLockLog_CheckedChanged(object sender, EventArgs e)
        {
            try
            {

                logControl.IsLock = checkBoxLockLog.Checked;
            }
            catch (Exception ex)
            {
                Loger.Error(ex);
            }
        }


        private ThreadPoolEx _threadPool = null;
        private int _count = 0;
        private bool _runing = false;
        private void btnTestFor_Click(object sender, EventArgs e)
        {
            if (this._threadPool == null)
            {
                this._threadPool = new ThreadPoolEx(new int[] { 0, 1, 2, 3 });
                Loger.Info("create ThreadPoolEx");
            }

            if (this._runing)
            {
                Loger.Warn("正在运行.");
                return;
            }

            this._runing = true;
            Task.Factory.StartNew(() =>
            {
                _count = 0;
                Loger.Info($"开始 {_count}");

                ThreadPoolExcuteResult result = this._threadPool.For(0, 50, (i) =>
                {
                    var betinTimestamp = TimeEx.GetTimestamp();
                    while (TimeEx.GetTimestamp() - betinTimestamp < 1000)
                    {

                    }

                    var count = Interlocked.Increment(ref _count);
                    Loger.Debug($"{Thread.CurrentThread.ManagedThreadId}    i:{i} count:{count}");
                });
                Loger.Info($"完成 {_count}  result:{result.ToString()}");
                this._runing = false;
            });
        }





        private void btnTestForeach_Click(object sender, EventArgs e)
        {
            if (this._threadPool == null)
            {
                this._threadPool = new ThreadPoolEx(new int[] { 0, 1, 2, 3 });
                Loger.Info("create ThreadPoolEx");
            }

            if (this._runing)
            {
                Loger.Warn("正在运行.");
                return;
            }

            this._runing = true;
            Task.Factory.StartNew(() =>
            {
                _count = 0;
                Loger.Info($"开始 {_count}");
                int[] arr = new int[100];
                for (int i = 0; i < arr.Length; i++)
                {
                    arr[i] = i;
                }

                ThreadPoolExcuteResult result = this._threadPool.ForEach(arr, (item) =>
                {
                    var betinTimestamp = TimeEx.GetTimestamp();
                    while (TimeEx.GetTimestamp() - betinTimestamp < 1000)
                    {

                    }

                    var count = Interlocked.Increment(ref _count);
                    Loger.Debug($"{Thread.CurrentThread.ManagedThreadId}    item:{item} count:{count}");
                });
                Loger.Info($"完成 {_count}  result:{result.ToString()}");
                this._runing = false;
            });
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (this._threadPool != null)
            {
                this._threadPool.Cancell();
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.logControl.Clear();
        }
    }
}
